package com.ls.fw.office;
 
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
 
/**
 * 
 * @author lisheng
 * 2016年9月6日 下午10:20:45
 * @version V1.0
 */
public class CsvWriter {
     
    //CSV文件分隔符
    private static final String NEW_LINE_SEPARATOR = "\n";
     
    private CSVPrinter csvWriter = null;
    
    public static final  CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
     
    public CsvWriter(StringWriter sw,CSVFormat format) throws IOException{
        this.csvWriter = new CSVPrinter(sw, format);
    }
    
    public CsvWriter(String path,CSVFormat format) throws IOException{
        this.csvWriter = new CSVPrinter(new FileWriter(path), format);
    }

    public CsvWriter(OutputStream os,CSVFormat format) throws IOException{
        this.csvWriter = new CSVPrinter(new OutputStreamWriter(os), format);
    }

    public CsvWriter(StringWriter sw) throws IOException{
        this.csvWriter = new CSVPrinter(sw, csvFileFormat);
    }
    
    public CsvWriter(String path) throws IOException{
        this.csvWriter = new CSVPrinter(new FileWriter(path), csvFileFormat);
    }

    public CsvWriter(final Appendable out, final CSVFormat format) throws IOException{
        this.csvWriter = new CSVPrinter(out, format);
    }
    
    public CsvWriter(OutputStream os,String charSet) throws IOException{
        this.csvWriter = new CSVPrinter(new OutputStreamWriter(os,charSet), csvFileFormat);
    }
    
    public CsvWriter add(final Iterable<?> values) throws IOException {
    	csvWriter.printRecord(values);
    	return this;
    }

    public CsvWriter add(final Object... values) throws IOException {
    	csvWriter.printRecord(values);
    	return this;
    }
    
    public CSVPrinter getCSVPrinter(){
    	return csvWriter;
    }
     
    public void close(){
    	 try {
    		 csvWriter.flush();
             csvWriter.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }
    
     
    /**
     * @param args
     */
    public static void main(String[] args){
        
    }
     
}